#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project : POS_api_test_project 
@File    : testcase_template.py
@IDE     : PyCharm 
@Author  : Mario
@Date    : 2022/5/26 19:08 
@Describe: pytest用例模板
"""
import os
import datetime
from Utils.readFilesUtils.yamlControl import GetYamlData
from Config.setting import ConfigHandler


def write_case(case_path, page):
    with open(case_path, 'w', encoding='utf-8') as f:
        f.write(page)


def write_testcase_file(allure_epic, allure_feature, class_title,
                        func_title, case_path, yaml_path, file_name, allure_story):
    """
    生成pytest用例代码
    :param allure_epic: 项目名称
    :param allure_feature: 模块名称
    :param class_title: 类名称
    :param func_title: 函数名称
    :param case_path: case 路径
    :param yaml_path: yaml 文件路径
    :param file_name: 文件名称
    :param allure_story: 用例内容
    :return: pytest用例模板
    """
    config_data = GetYamlData(ConfigHandler.CONFIG_PATH).get_yaml_data()
    # TODO(钟昀): 后续优化为从每个用例的yaml文件取值
    author = config_data['TesterName']
    now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    # 用例热加载
    real_time_update_test_cases = config_data['real_time_update_test_cases']
    template = f'''#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Date    : {now_time}
@Author  : {author}
@Describe: Automatically generated pytest case
"""
import allure
import pytest
from Config.setting import ConfigHandler
from Utils.readFilesUtils.get_yaml_data_analysis import CaseData
from Utils.assertUtils.assertControl import Assert
from Utils.requestsUtils.posRequestControl import PosRequestControl
from Utils.readFilesUtils.regularControl import regular, cache_regular
from Utils.requestsUtils.teardownControl import TearDownHandler


TestData = CaseData(ConfigHandler.TEST_CASE_DATA_PATH + r'{yaml_path}').case_process()
re_data = regular(str(TestData))


@allure.epic("{allure_epic}")
@allure.feature("{allure_feature}")
class Test{class_title}:

    @allure.story("{allure_story}")
    @pytest.mark.parametrize('in_data', eval(re_data), ids=[i['detail'] for i in TestData])
    def test_{func_title}(self, in_data, case_skip):
        """ Automatically generated pytest function """
        in_data = eval(cache_regular(str(in_data)))
        res = PosRequestControl().http_requests(in_data)
        TearDownHandler().teardown_handle(res)
        Assert(in_data['assert']).assert_equality(response_data=res['response_data'], 
                                                  sql_data=res['sql_data'], status_code=res['status_code'])


if __name__ == '__main__':
    pytest.main(['{file_name}', '-s', '-W', 'ignore:Module already imported:pytest.PytestWarning'])
'''
    if real_time_update_test_cases:
        write_case(case_path=case_path, page=template)
    elif real_time_update_test_cases is False:
        if not os.path.exists(case_path):
            write_case(case_path=case_path, page=template)
    else:
        raise ValueError('real_time_update_test_cases 配置不正确,只能配置 True 或者 False')
